package com.hsl.housaileibot001.controller;

import com.hsl.housaileibot001.ai.service.AiChatService;
import com.hsl.housaileibot001.common.Result;
import com.hsl.housaileibot001.document.MockQuestion;
import com.hsl.housaileibot001.model.vo.MockExamVO;
import com.hsl.housaileibot001.service.MockQuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liul
 * @date 2025/10/19 0:44
 */
@Tag(name = "AI接口", description = "AI相关接口")
// @RestController
@RequestMapping("/ai")
public class AiController {
    @Resource
    private AiChatService aiChatService;
    
    @Resource
    private MockQuestionService mockQuestionService;

    @Operation(summary = "流式聊天", description = "与AI进行流式对话")
    @GetMapping("/chat")
    public Flux<ServerSentEvent<String>> chat(
            @Parameter(description = "记忆ID") int memoryId, 
            @Parameter(description = "用户消息") String userMessage) {
        return aiChatService.chatStream(memoryId, userMessage)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk)
                        .build());
    }

    @Operation(summary = "生成模拟题", description = "根据用户需求生成模拟面试题")
    @PostMapping("/generate-mock-exam")
    public Result<MockExamVO> generateMockExam(
            @Parameter(description = "面试题ID") @RequestParam Long interviewQuestionId,
            @Parameter(description = "用户需求描述") @RequestParam String userMessage) {
        try {
            // 先检查 MongoDB 中是否已经有该面试题的模拟题
            List<MockQuestion> existingQuestions = mockQuestionService.findActiveByInterviewQuestionId(interviewQuestionId);
            
            MockExamVO mockExam;
            
            if (existingQuestions != null && !existingQuestions.isEmpty()) {
                // 如果已经有模拟题，直接返回缓存的数据
                mockExam = new MockExamVO();
                mockExam.setInterviewQuestionId(interviewQuestionId);
                mockExam.setMockQuestions(existingQuestions.stream()
                        .map(MockQuestion::toVO)
                        .collect(Collectors.toList()));
            } else {
                // 如果没有缓存，调用 AI 生成模拟题
                mockExam = aiChatService.chatWithSoftwareArchitect(userMessage);
                mockExam.setInterviewQuestionId(interviewQuestionId);
                
                // 保存模拟题到 MongoDB
                if (mockExam.getMockQuestions() != null && !mockExam.getMockQuestions().isEmpty()) {
                    for (MockExamVO.MockQuestion mockQuestionVO : mockExam.getMockQuestions()) {
                        try {
                            // 创建MongoDB文档实体，直接使用VO对象
                            MockQuestion mockQuestion = new MockQuestion(interviewQuestionId, mockQuestionVO);
                            
                            // 保存到 MongoDB
                            mockQuestionService.save(mockQuestion);
                        } catch (Exception e) {
                            // 记录错误但不中断整个流程
                            System.err.println("保存模拟题到MongoDB失败: " + e.getMessage());
                        }
                    }
                }
            }
            
            return Result.success(mockExam);
        } catch (Exception e) {
            return Result.error("生成模拟题失败：" + e.getMessage());
        }
    }
}
